package bjut.zrpc.core.optimization.loadbalance;

import bjut.zrpc.core.optimization.factory.SingletonFactory;
import bjut.zrpc.core.optimization.message.ZRpcRequestMessage;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/28 19:39
 */
public class StickinessLoadBalance extends AbstractLoadBalance {

    private static final ConcurrentHashMap<String, String> STICKINESS_SERVICE_MAP = new ConcurrentHashMap<>();
    private static final ConcurrentHashMap<String, Integer> SERVICE_COUNT_MAP = new ConcurrentHashMap<>();

    @Override
    protected String doSelect(List<String> serviceList, ZRpcRequestMessage zRpcRequestMessage) {

        String serviceInfo = zRpcRequestMessage.getServiceInfo();
        String serviceAddress = STICKINESS_SERVICE_MAP.get(serviceInfo);
        if (serviceAddress == null || SERVICE_COUNT_MAP.get(serviceAddress) > 5) {
            Random random = new Random();
            serviceAddress = serviceList.get(random.nextInt(serviceList.size()));
            STICKINESS_SERVICE_MAP.put(serviceInfo, serviceAddress);
            SERVICE_COUNT_MAP.put(serviceAddress, 0);
        }
        SERVICE_COUNT_MAP.put(serviceAddress, SERVICE_COUNT_MAP.get(serviceAddress) + 1);
        return serviceAddress;
    }
}
